<?php

    $mikron->Site->main();
    $mikron->Modules->LoadModule('slidewindow');

    function getCity($ipadr = null)
    {
        global $mikron;
        $city = $mikron->Cache->getCache("usercity");
        if(!is_null($city))
        {
            return $city;
        }
        // return "Казань";
        if(is_null($ipadr))
        {
            $ipadr = $_SERVER["REMOTE_ADDR"];
        }
        $data = "<ipquery><fields><city/></fields><ip-list><ip>$ipadr</ip></ip-list></ipquery>";
        $url = "http://194.85.91.253:8090/geo/geo.html";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url); // set url to post to
        curl_setopt($ch, CURLOPT_FAILONERROR, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);// allow redirects
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
        curl_setopt($ch, CURLOPT_TIMEOUT, 3); // times out after 4s
        curl_setopt($ch, CURLOPT_POST, 1); // set POST method
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // add POST fields
        $result = curl_exec($ch); // run the whole process
        curl_close($ch);
        // $result = iconv("windows-1251", "UTF-8", $result);
        // echo $result;
        $doc = new DOMDocument();
        $doc->loadXML($result);
        $content = $doc->getElementsByTagname('ip-answer');
        $city = null;
        foreach($content as $value)
        {
            $ip_blocks = $value->getElementsByTagname('ip');
            foreach($ip_blocks as $ip_value)
            {
                if($ip_value->hasAttribute('value'))
                {
                    $ip = $ip_value->getAttribute('value');
                    
                    $city_value = $ip_value->getElementsByTagname('city');
                    foreach($city_value as $cities)
                    {
                        $city = $cities->nodeValue;
                    }
                }
            }
        }
        unset($content);
        $mikron->Cache->setCache("usercity", is_null($city)?'Unknown':$city);
        return $city;
    }

?>